﻿/*----------------------------------------------------------------
// 公司名称：公司名称
// 
// 产品名称：Gaf
//
// 创 建 人：netcasewqs
// 创建日期：2022/3/4
// 邮    箱：netcasewqs@qq.com
//
// Copyright (C) 2022 Gaf，保留所有权利。
//
//----------------------------------------------------------------*/
namespace Gaf.Impl;

record ParameterDescriptor(ParameterInfo Parameter, int Order);

record ConstructorInvoker(ConstructorInfo Constructor, ParameterInfo? Assemblies, ParameterInfo? Manifest)
{
    private static readonly object[] EmptyArray = new object[0];

    private object? GetParameterValue(ParameterInfo p, IEnumerable<Assembly> assemblies, IConfiguration? manifest = null)
    {
        if (ActivatorDescriptor.IsAssembliesParameter(p)) return assemblies;
        if (ActivatorDescriptor.IsManifestParameter(p)) return manifest;
        return null;
    }

    public object Invoke(IEnumerable<Assembly> assemblies, IConfiguration? manifest)
    {
        try
        {
            var ps = Constructor.GetParameters();
            if (ps.Length == 0)
            {
                return Constructor.Invoke(EmptyArray);
            }

            var args = new object?[ps.Length];
            for (int i = 0; i < ps.Length; i++)
            {
                args[i] = GetParameterValue(ps[i], assemblies, manifest);
            }
            return Constructor.Invoke(args);
        }
        catch (TargetInvocationException ex)
        {
            throw ex.InnerException!;
        }
    }
}

